package edu.xidian.onlinedocument.repository;

import edu.xidian.onlinedocument.entity.*;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Repository
public interface UserTokenJPARepository extends JpaRepository<UserTokenData, Integer> {

    boolean existsUserTokenByUserId(int userId);

    boolean existsUserTokenByUserToken(String userToken);

    /**
     * 存储token
     * @param userId userId
     * @param token token
     * @param createTime createTime
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    @Modifying
    @Query(nativeQuery = true, value = "insert into user_id_token values(:user_id, :user_token, :token_create_time)")
    void saveUserToken(@Param("user_id") int userId,
              @Param("user_token") String token,
              @Param("token_create_time") Date createTime);

    /**
     * 查询token
     * @param userToken token
     * @return UserToken
     */
    // @Query(nativeQuery = true, value = "select * from user_id_token where user_token = :token")
    UserTokenData findUserTokenByUserToken(/*@Param("token") */String userToken);

    /**
     * 查询token
     * @param userId user id
     * @return UserToken
     */
    // @Query(nativeQuery = true, value = "select * from user_id_token where user_id = :u_id")
    UserTokenData findUserTokenByUserId(/*@Param("user_id") */int userId);

    /**
     * 根据用户id删除token
     * @param userId user id
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    @Modifying
    // @Query(nativeQuery = true, value = "delete from user_id_token where user_id = :u_id")
    void deleteUserTokenByUserId(/*@Param("user_id") */int userId);

    /**
     * 根据用户账号删除token
     * @param userNum userNum
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    @Modifying
    /*@Query(nativeQuery = true, value = "delete from user_id_token where user_id = " +
                                        "(select user_id from user_data where user_num = :user_num)")*/
    void deleteUserTokenByUserData_UserNum(/*@Param("user_num") */String userNum);
}
